<template>
  <div class="container">
    <div class="history-search">
      <div>
        <span>设备编码：{{ this.$route.query.id }}</span>
        <span>设备名称：
          <dict-tag :type="DICT_TYPE.RK_DEVICE_TYPE" :value="this.$route.query.id" />
        </span>
      </div>
      <el-form :model="queryParams" ref="queryForm">
        <el-form-item>
          <el-radio-group v-model="radioTime" size="mini">
            <el-radio :label="'today'" border>当天</el-radio>
            <el-radio :label="'thisMonth'" border>当月</el-radio>
            <el-radio :label="'lastHalfYear'" border>半年</el-radio>
            <el-radio :label="'lastOneYear'" border>一年</el-radio>
            <el-date-picker v-model="pickTime" style="width: 240px; margin-left: 10px"
                            value-format="yyyy-MM-dd HH:mm:ss" type="daterange" range-separator="-"
                            start-placeholder="开始日期"
                            end-placeholder="结束日期" :default-time="['00:00:00', '23:59:59']" size="mini"/>
          </el-radio-group>
        </el-form-item>
      </el-form>
    </div>
    <el-card class="box-card">
      <div class="title">历史数据</div>
      <line-chart v-if="tableData.length>0" :chart-data="lineChartData" :height="'600px'"/>
      <div v-else class="no-data">No Data</div>
    </el-card>
    <div class="list-card">
      <div v-if="tableData.length>0">
        <el-card style="padding-top: 20px">
          <!-- 列表 -->
          <el-table v-loading="loading" :data="pageData" :tree-props="{children: 'data', hasChildren: 'hasChildren'}">>
            <el-table-column label='设备名称' align="center" prop="deviceAddr"></el-table-column>
            <el-table-column label="数据记录时间" align="center" prop="recordTimeStr"></el-table-column>
            <el-table-column label="寄存器名称及单位" align="center" prop="registerName">
              <!--              <template v-slot="scope">
                              <dict-tag :type="DICT_TYPE.EQUIPMENT_ACQUISITION_INFO_E_NUM" :value="scope.row.enum" />
                            </template>-->
            </el-table-column>
            <el-table-column label="数据结果" align="center" prop="value"></el-table-column>
          </el-table>
          <el-pagination
            style="margin-top: 12px;text-align: right;"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="currentPage"
            :page-sizes="[10, 20, 30, 50]"
            :page-size="pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total">
          </el-pagination>
        </el-card>
      </div>
    </div>
  </div>
</template>

<script>
import LineChart from '../../dashboard/LineChart'
import {getDate} from '@/utils/timeUtil'
import {getRkHistoryData} from '@/api/equipment/info'
import _ from "lodash";

export default {
  components: {
    LineChart
  },
  data() {
    return {
      lineChartData: {
        xData: [],
        yData: {}
      },
      // 遮罩层
      loading: true,
      // 总条数
      total: 0,
      // 溯源信息列表
      tableData: [],
      pageData:[],
      currentPage: 1,
      pageSize: 10,
      queryParams: {
        deviceAddr: null,
      },
      pickTime: [],
      radioTime: 'thisMonth'
    }
  },
  created() {
    this.queryParams.startTime = getDate(this.radioTime).startTime + '00:00:00'
    this.queryParams.endTime = getDate(this.radioTime).endTime + '23:59:59'
    this.getList()
  },
  watch: {
    radioTime(val) {
      if (val !== '') {
        this.currentPage= 1
        this.queryParams.startTime = getDate(val).startTime + '00:00:00'
        this.queryParams.endTime = getDate(val).endTime + '23:59:59'
        this.pickTime = undefined
        this.getList()
      }
    },
    pickTime(val) {
      if (val !== undefined) {
        this.currentPage= 1
        this.radioTime = ''
        this.queryParams.startTime = val[0]
        this.queryParams.endTime = val[1]
        this.getList()
      }
    }
  },
  methods: {
    /** 查询列表 */
    getList() {
      this.loading = true
      // 执行查询
      this.queryParams.deviceAddr = parseInt(this.$route.query.id)
      this.queryParams.nodeId = -1
      //  土壤墒情二
      getRkHistoryData(this.queryParams).then(response => {
        this.loading = false
        this.lineChartData = {
          xData: [],
          yData: []
        }
        this.tableData = []
        response.data.forEach(k => {
          k.data.map((item) => {
            let arr = ['ph', '温度','溶解氧饱和度','溶解氧浓度','电导率']
            if (arr.indexOf(item.registerName) !== -1) {
              this.tableData.push({
                recordTimeStr: k.recordTimeStr,
                deviceAddr: k.deviceAddr,
                registerName: item.registerName,
                value: item.value
              })
            }
          })
        })
        this.total = this.tableData.length
        this.pageData = this.queryByPage()
        // 去重
        this.lineChartData.xData = [...new Set(this.tableData.map(item => item.recordTimeStr))]
        // 时间排序
        this.lineChartData.xData.sort((a, b) => {
          return new Date(a) - new Date(b)
        })
        let end = []
        this.lineChartData.xData.forEach((i, o) => {
          end.push({ recordTimeStr: i, list: [] })
        })
        // 数据整理
        end.map((it, id) => {
          this.tableData.forEach((item,index)=>{
            if (it.recordTimeStr === item.recordTimeStr) {
              it.list.push({
                recordTimeStr: item.recordTimeStr,
                deviceAddr: item.deviceAddr,
                registerName:item.registerName,
                value: item.value,
              })
            }
          })
        })
        end.forEach((item,key)=>{
          // 补全部分数据
          let arr = [...new Set(this.tableData.map(item => item.registerName))]
          arr.forEach(k=>{
            let arr1= [...new Set(item.list.map(item => item.registerName))]
            if(arr1.indexOf(k)===-1){
              item.list.push({
                registerName:k,
                value: null,
              })
            }
          })
          // 图表y轴数据
          item.list.map(t=>{
            if (!this.lineChartData.yData[t.registerName]) {
              this.lineChartData.yData[t.registerName] = []
            }
            this.lineChartData.yData[t.registerName].push({
              name:t.registerName,
              num: t.value
            })
          })
        })
      })
    },
    // 改变每页大小的回调
    handleSizeChange (val) {
      this.pageSize = val
      this.pageData = this.queryByPage()
    },
    // 改变当前页的回调
    handleCurrentChange (val) {
      this.currentPage = val
      this.pageData = this.queryByPage()
    },
    // 实现分页的方法
    queryByPage () {
      //使用lodash对http请求数据按时间进行排序
      this.tableData = _.sortBy(this.tableData, 'recordTimeStr')
      // 起始位置 = (当前页 - 1) x 每页的大小
      const start = (this.currentPage - 1) * this.pageSize
      // 结束位置 = 当前页 x 每页的大小
      const end = this.currentPage * this.pageSize
      return this.tableData.slice(start, end)
    }
  }
}
</script>

<style lang='scss' scoped>
.container {
  padding: 0 24px 24px;
  background-color: rgb(240, 242, 245);
  min-height: calc(100vh - 86px);

  .history-search {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 10px 0;

    .el-form-item {
      margin: auto 0;
    }

    span {
      margin-left: 8px;
    }

    .el-radio--mini {
      margin-right: 0;
      background: #fff;
    }

    ::v-deep .el-radio__input {
      display: none;
    }
  }

  .box-card {
    .title {
      font-size: 18px;
      font-weight: bold;
    }

    .no-data {
      height: 600px;
      font-size: 28px;
      text-align: center;
      line-height: 600px;
    }
  }

  .list-card {
    margin-top: 20px;

    .el-card__body {
      padding: 30px;
    }
  }
}
</style>
